import Vue from "vue";
import Router from "vue-router";
import { Dialog } from "vant";
//非组件不能直接加载
import store from "../store";

Vue.use(Router);

const routes = [
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login"),
    meta: { requiresAuth: false } //是否需要登录
  },
  {
    path: "/",
    component: () => import("../views/layout"),
    children: [
      {
        path: "",
        name: "home",
        component: () => import("../views/home"),
        meta: { requiresAuth: false } //是否需要登录
      },
      {
        path: "/qa",
        name: "qa",
        component: () => import("../views/qa"),
        meta: { requiresAuth: false } //是否需要登录
      },
      {
        path: "/video",
        name: "video",
        component: () => import("../views/video"),
        meta: { requiresAuth: false } //是否需要登录
      },
      {
        path: "/my",
        name: "my",
        component: () => import("../views/my"),
        meta: { requiresAuth: false } //是否需要登录
      }
    ]
  },
  {
    path: "/search",
    name: "search",
    component: () => import("../views/search"),
    meta: { requiresAuth: false } //是否需要登录
  },
  {
    path: "/neirong/:articleId",
    name: "neirong",
    component: () => import("../views/neirong"),
    // 将动态路由参数映射到组件的props中 ，无论是访问和维护性都很方便
    props: true,
    meta: { requiresAuth: false } //是否需要登录
  },
  {
    path: "/userprofile",
    name: "userProfile",
    component: () => import("../views/userProfile"),
    // 将动态路由参数映射到组件的props中 ，无论是访问和维护性都很方便
    meta: { requiresAuth: false } //是否需要登录
  },
  {
    path: "/userchat",
    name: "userChat",
    component: () => import("../views/userChat"),
    // 将动态路由参数映射到组件的props中 ，无论是访问和维护性都很方便
    meta: { requiresAuth: true } //是否需要登录
  }
];

const router = new Router({
  routes
});

router.beforeEach((to, from, next) => {
  // 校验登录状态
  if (to.meta.requiresAuth) {
    if (store.state.user) {
      return next();
    }
    Dialog.confirm({
      title: "访问提示",
      message: "该功能需要登录才能访问，确认登录吗"
    })
      .then(() => {
        // on close
        // 跳转页面
        router.replace({
          name: "login",
          query: {
            redirect: router.currentRoute.fullPath
          }
        });
      })
      .catch(() => {
        // 取消停止导航
        next(false);
      });
  } else {
    // 不需要登录的直接过去
    next();
  }
});

export default router;
